package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.common.utils.FileUtils;
import com.leetroll.media.service.JobExecutor;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

import static com.leetroll.common.utils.FileUtils.toZip;

@Service
@Slf4j
public class Job_Evermotion {

    private static final String TO_DB_FILE_PATH = "F:\\_resources\\3d_model\\Evermotion\\入库\\2024-4-01-db-zip";
    private final ItemService itemService;
    private final UpDownloadService upDownloadService;
    private JobExecutor jobExecutor;

    @Autowired
    public Job_Evermotion(ItemService itemService, UpDownloadService upDownloadService, JobExecutor jobExecutor) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
        this.jobExecutor = jobExecutor;
    }

    public void upload() throws InterruptedException, IOException, ExecutionException {
        File folder = new File(TO_DB_FILE_PATH);
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] folders = folder.listFiles();
        if (folders == null) return;

        for (File itemsFolder : folders) {
            log.info(">>>>>>>>>>>>>>>> 准备插入: {}", itemsFolder.getName());
            for (File itemFolder : Objects.requireNonNull(itemsFolder.listFiles())) {
                jobExecutor.submit(() -> uploadAttach(itemFolder));
            }
        }
        jobExecutor.await();
    }

    private Integer uploadFile(File itemFolder) {
        log.info("----------------------准备插入 item[{}]----------------------", itemFolder.getName());
        File[] files = itemFolder.listFiles();
        if (files == null) return 1;

        //插入item表
        String name = itemFolder.getName();
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
        item.setCatId(7L);
        item.setStatus("show");
        item.setSource("Evermotion");
        item.setAuthor("~");
        item.setPrice(15.0);
        item.setMark("");
        item.setType(EItemType.MODEL.getType());
        item.setDesp("");
        item.setTag("furniture");
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        for (File file : files) {
            if (file.isFile()) continue;
            if (file.getName().equals("main")) {
                //插入主图文件
                File mainFile = Objects.requireNonNull(file.listFiles())[0];
                upDownloadService.upload2AliByType(item.getId(), mainFile, EFileType.MAIN);
                log.info("\t\t\t>> 主图插入成功");
            } else if (file.getName().equals("prev")) {
                //插入预览图文件
                for (File preFile : Objects.requireNonNull(file.listFiles())) {
                    upDownloadService.upload2AliByType(item.getId(), preFile, EFileType.PREVIEW);
                }
                log.info("\t\t\t>> 预览图插入成功");
            } else if (file.getName().equals("attach")) {
                File attachFile = file.listFiles()[0].listFiles()[0];
//                File attachFile = new File("C:\\Users\\quxiaoyu\\Desktop\\test\\attach.zip");
//                upDownloadService.upload2AliByType(item.getId(), attachFile, EFileType.ATTACHMENT);

                //给附件文件夹添加itemId层级  方便后续单独插入附件文件
                if (item.getId() != null) {
                    String attachFilepath = attachFile.getParentFile().getParentFile() + "\\" + item.getId();
                    FileUtils.creatDir(attachFilepath);
                    attachFile.renameTo(new File(attachFilepath + "\\" + attachFile.getName()));
                    attachFile.getParentFile().delete();
                }

                log.info("\t\t\t>> 附件插入成功");
            }
        }
        return 1;
    }

    private Integer uploadAttach(File itemFolder) {
        File[] files = itemFolder.listFiles();
        if (files == null) return 1;
        for (File file : files) {
            if (file.isFile()) continue;
            if (!file.getName().equals("attach")) continue;
            Long itemId = Long.valueOf(file.listFiles()[0].getName());
            File attachFile = file.listFiles()[0].listFiles()[0];

            try {
                upDownloadService.upload2AliByType(itemId, attachFile, EFileType.ATTACHMENT);
            } catch (Exception e) {
                log.error("fail to upload attach >> {}", itemId);
            }
            log.info("\t\t\t>> 附件插入成功");
        }
        return 1;
    }

    public static void main(String[] args) throws IOException {
//        String srcPath = "F:\\_resources\\3d_model\\Evermotion\\EvermotionArchmodelsVol.227";
//        String targetPath = "F:\\_resources\\3d_model\\Evermotion\\入库\\2024-3-28-db-zip\\ArchmodelsVol.227\\";
//        handle2(srcPath, targetPath);

        File attachFile = new File("C:\\Users\\quxiaoyu\\Desktop\\test\\888\\attach.zip");
        String attachFilepath = attachFile.getParentFile().getParentFile() + "\\" + 999;
        FileUtils.creatDir(attachFilepath);
        attachFile.renameTo(new File(attachFilepath + "\\" + attachFile.getName()));
        attachFile.getParentFile().delete();
        log.info("finished");
    }

    /**
     * 构建入库文件夹
     */
    public static void handle1(String srcPath, String targetPath) throws IOException {
        for (File folder : Objects.requireNonNull(new File(srcPath).listFiles())) {
            if (!folder.isDirectory()) continue;
            //创建文件夹
            String mainPath = targetPath + folder.getName() + "\\main\\";
            String prevPath = targetPath + folder.getName() + "\\prev\\";
            String attachPath = targetPath + folder.getName() + "\\attach\\";
            FileUtils.creatDir(mainPath);
            FileUtils.creatDir(prevPath);
            FileUtils.creatDir(attachPath);

            toZip(folder.getAbsolutePath(), attachPath + folder.getName() + ".zip");

            File[] listFiles = folder.listFiles();
            for (File file : Objects.requireNonNull(listFiles)) {
                if (file.isDirectory()) continue;
                if (file.getName().endsWith("jpg") || file.getName().endsWith("png")) {
                    FileUtils.copyFile(file.getAbsolutePath(), prevPath + file.getName());
                    if (file.getName().contains("Cam_001_day")) {
                        FileUtils.copyFile(file.getAbsolutePath(), mainPath + file.getName());
                    }
                }
            }
        }
    }

    public static void handle2(String srcPath, String targetPath) throws IOException {
        List<String> names = new ArrayList<>();
        for (File folder : Objects.requireNonNull(new File(srcPath).listFiles())) {
            if (folder.getName().equals("Renders")) {
                for (File file : Objects.requireNonNull(folder.listFiles())) {
                    names.add(file.getName().split("\\.")[0]);
                }
            }
        }

        for (String name : names) {
            //创建文件夹
            String mainPath = targetPath + name + "\\main\\";
            String prevPath = targetPath + name + "\\prev\\";
            String attachPath = targetPath + name + "\\attach\\";
            String attachFilePath = targetPath + name + "\\attach_file\\";
            FileUtils.creatDir(mainPath);
            FileUtils.creatDir(prevPath);
            FileUtils.creatDir(attachPath);

            for (File folder : Objects.requireNonNull(new File(srcPath).listFiles())) {
                if (!folder.isDirectory()) continue;
                for (File file : Objects.requireNonNull(folder.listFiles())) {
                    if (file.getName().toLowerCase().contains(name.toLowerCase())) {
                        FileUtils.creatDir(attachFilePath + folder.getName() + "\\");
                        FileUtils.copyFile(file.getAbsolutePath(), attachFilePath + folder.getName() + "\\" + file.getName());
                    }
                }
                if (folder.getName().equals("Renders") || folder.getName().equals("Render") || folder.getName().equals("AM257_Renders")) {
                    for (File file : Objects.requireNonNull(folder.listFiles())) {
                        if (file.getName().toLowerCase().contains(name.toLowerCase())) {
                            FileUtils.copyFile(file.getAbsolutePath(), mainPath + file.getName());
                            FileUtils.copyFile(file.getAbsolutePath(), prevPath + file.getName());
                        }
                    }
                }
            }

            toZip(attachFilePath, attachPath + name + ".zip");
            FileUtils.deleteFolder(new File(attachFilePath));
        }

    }
}
